package android.mcsmtms.activity;

import java.math.BigDecimal;
import java.math.RoundingMode;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.mcsmtms.R;
import android.mcsmtms.constant.GlobalConstants.GPSConstants;
import android.mcsmtms.manager.GPSCallback;
import android.mcsmtms.manager.GPSManager;
import android.mcsmtms.manager.SpeedManager;
import android.mcsmtms.settings.AppSettings;
import android.mcsmtms.util.Utilities;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MonitorSpeedActivity extends Activity implements GPSCallback {
	private GPSManager gpsManager = null;
	private static Handler enableGpsHandler;
	private TextView speedTextView;
	private AbsoluteSizeSpan sizeSpanLarge = null;
	private AbsoluteSizeSpan sizeSpanSmall = null;
	private SpeedManager speedManager;
	private double speed = 0.0;
	private int measurement_index;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 setContentView(R.layout.activity_monitor_speed);

		Button monitorSpeedBtn = (Button) findViewById(R.id.hazard_map_btn);
		monitorSpeedBtn.setOnClickListener(hazardMapOnClickListener);

		// Speed
		gpsManager = new GPSManager();
		gpsManager.startListening(getApplicationContext());
		gpsManager.setGPSCallback(this);

//		Button sendReportBtn = (Button) findViewById(R.id.send_report_btn);
//		sendReportBtn.setOnClickListener(sendReportOnClickListener);

		enableGpsHandler = new Handler() {
			public void handleMessage(Message msg) {
				Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
				MonitorSpeedActivity.this.startActivity(intent);
			}
		};

		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		boolean isGpsEnabled = gpsManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);

		if (isGpsEnabled) {
			// Location providers enabled
			Toast.makeText(this, "GPS Enabled: " + provider, Toast.LENGTH_LONG)
					.show();
		} else {
			Utilities.showDefaultAlertDialog(this,
					"Enable GPS",
					"Enable GPS", enableGpsHandler);
		}

		// init of textviews
		speedTextView = (TextView) findViewById(R.id.speed_label_value);
		// averageSpeedTextView = (TextView)
		// findViewById(R.id.label_average_speed_value);

		setSpeedText(0.00);
		speedManager = new SpeedManager();

		// get saved preferences
//		minSpeedPercentage = AppSettings.getMinSpeedPercentageInt(this);
		measurement_index = AppSettings.getMeasureUnit(this);

//		TextView minSpeedPercentageTextView = (TextView) findViewById(R.id.label_min_speed_percentage_value);
//		minSpeedPercentageTextView.setText(String.valueOf(minSpeedPercentage));
//
//		setAverageSpeedText(0.00);
//
//		speedManager = new SpeedManager();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.monitor_speed, menu);
		return true;
	}

	private View.OnClickListener hazardMapOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent openHazardMapActivityIntent = new Intent(
					MonitorSpeedActivity.this, McsmtmsActivity.class);
			startActivity(openHazardMapActivityIntent);
		}
	};

	@Override
	public void onGPSUpdate(Location location) {
		String title = "";
		String message = "";

		speedManager.addLocation(location);

//		((TextView) findViewById(R.id.label_lat_value)).setText(String
//				.valueOf(roundDecimal(location.getLatitude(), 2)));
//		((TextView) findViewById(R.id.label_long_value)).setText(String
//				.valueOf(roundDecimal(location.getLongitude(), 2)));

		if (location.hasSpeed())
			speed = roundDecimal(convertSpeed(location.getSpeed()), 2);
		else
			speed = roundDecimal(convertSpeed(speedManager.computeCurrentSpeed()), 2);

//		averageSpeed = roundDecimal(speedManager.getAverageSpeed(), 2);

		setSpeedText(speed);
//		setAverageSpeedText(averageSpeed);
//		if (speed < (speedManager.getAverageSpeed() * minSpeedPercentage)
//				&& promptDialog == null) {
//
//			promptDialog = Utilities.showDefaultAlertDialog(this,
//					promptOkOnClickListener, promptCancelOnClickListener,
//					title, message);
//			startCountDownForDialog();
//		}

		//speedIntervalTimer.start();
	}

	@Override
	protected void onDestroy() {
		try {
			if (gpsManager != null) {
				gpsManager.stopListening();
				gpsManager.setGPSCallback(null);
				gpsManager = null;
			}
		} catch (Exception ex) {
			// TODO: Replace with appropriate error dialog.
			Toast.makeText(
					MonitorSpeedActivity.this,
					"Error in stopping GPS Manager: "
							+ ex.getLocalizedMessage(), Toast.LENGTH_LONG)
					.show();
		}
		super.onDestroy();
	}
	
	private void setSpeedText(double value) {
		String speedText = String.valueOf(value) + " "
				+ AppSettings.getMeasureUnitString(this);
		Spannable span = new SpannableString(speedText);
		int firstPos = speedText.indexOf(32);

		span.setSpan(sizeSpanLarge, 0, firstPos,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(sizeSpanSmall, firstPos + 1, speedText.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		speedTextView.setText(span);
	}

	private double convertSpeed(double speed) {
		return ((speed * GPSConstants.HOUR_MULTIPLIER) * GPSConstants.UNIT_MULTIPLIERS[measurement_index]);
	}
	
	private double roundDecimal(double value, final int decimalPlace) {
		double retValue = 0;
		try {
			BigDecimal bd = new BigDecimal(value);
	
			bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
			retValue = bd.doubleValue();
		} catch (Exception ex) {
			ex.printStackTrace();
			//Log.e(MonitorSpeed.class.getName(), ex.getMessage());
		}

		return retValue;
	}
}
